package com.zrf.gulimall.ware.listener;

import com.rabbitmq.client.Channel;
import com.zrf.gulimall.commnon.core.to.OrderTo;
import com.zrf.gulimall.commnon.core.to.mq.StockLockedTo;
import com.zrf.gulimall.ware.service.WareSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author zhanrf
 * @Date 2022/1/8 23:07
 */
@RabbitListener(queues = "stock.release.stock.queue")
@Component
@Slf4j
public class StockReleaseListener {
	@Autowired
	private WareSkuService wareSkuService;

	@RabbitHandler
	public void releaseStock(StockLockedTo to, Message message, Channel channel) throws IOException {
		log.info("******收到解锁库存的信息******");
		try {
			//当前消息是否被第二次及以后（重新）派发过来了
			// Boolean redelivered = message.getMessageProperties().getRedelivered();
			// 解锁库存
			wareSkuService.unlockStock(to);
			// 手动删除消息
			channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
		} catch (Exception e) {
			// 解锁失败 将消息重新放回队列，让别人消费
			channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
		}
	}

	@RabbitHandler
	public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {

		log.info("******收到订单关闭，准备解锁库存的信息******");

		try {
			wareSkuService.unlockStock(orderTo);
			// 手动删除消息
			channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
		} catch (Exception e) {
			// 解锁失败 将消息重新放回队列，让别人消费
			channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
		}
	}
}
